<?php
namespace app\home\logic;

use think\Model;

class Account extends Model {
    //送积分
    function sendScore($data = []) {
        if (!$data['user_id'] || !$data['nid']) {
            return null;
        }
        $re = model('credit_type')->getOne(['nid' => $data['nid']]);
        $score = $re['value'] ?: 0;
        //当前账户积分
        $account = model('account')->getOne(['user_id' => $data['user_id']]);

        $jfnid = $data['nid'] . "_" . $data['user_id'] . "_" . time();
        $balance_jf = $account['balance_jf'] + $score;

        model('jf_log')->add([
                'userid' => $data['user_id'],
                'nid' => $data['nid'],
                'run_jf' => $score,
                'balance_jf' => $balance_jf,
                'baizhu' => $data['beizhu'],
                'nid' => $jfnid
        ]);
        model('account')->updateBalanceJf([
                'score' => $score,
                'user_id' => $data['user_id']
        ]);
        return true;
    }

    /**
     *
     * @param Array $data =array("nid"=>"订单号","verify_remark"=>"审核备注","status"=>"审核状态")
     * @return Boolen
     */
    static function AddLog($data = array()) {

        //第一步，查询是否有资金记录
        $result = db('account_log')->where(['nid' => $data['nid']])->find();
        if ($result) {
            return ['code' => 0, 'msg' => "记录已存在"];
        }

        //第二步，查询原来的总资金
        $result = model('account')->getOne(['user_id' => $data['user_id']]);
        if (($result['frost'] + $data['frost']) < 0) {
            return ['code' => 0, 'msg' => "冻结资金不能小于0"];
        }

        //冻结资金,如果不可体现资金不够
        if ($data['frost'] > 0 && ($data['frost'] + $data['balance_frost']) == 0) { //冻结金额>0&&（冻结金额+不可提现）==0
            if ($data['frost'] > $result['balance']) {     //冻结资金>表中可用余额
                return ['code' => 0, 'msg' => "余额不足"];
            }
            if ($data['frost'] > $result['balance_frost']) {   //冻结金额>表中不可提现
                $data['balance_frost'] = -$result['balance_frost']; //不可提现= -表中不可提现
                $data['balance_cash'] = -($data['frost'] - $result['balance_frost']); //可提现= -(冻结金额-表中不可提现）
            }
        }
        //扣款,不可提现不够扣
        if ($data['balance_frost'] < 0) {
            if (-$data['balance_frost'] > $result['balance']) {
                return ['code' => 0, 'msg' => "余额不足"];
            }
            if ((-$data['balance_frost']) > $result['balance_frost']) {
                $data['balance_cash'] = $data['balance_frost'] + $result['balance_frost'];
                $data['balance_frost'] = -$result['balance_frost'];
            }
        }
        $prefix = config('database.prefix');
        //第三步，加入用户的财务记录
        $sql = "insert into `{$prefix}account_log` set ";
        $data['borrow_nid'] = isset($data['borrow_nid']) ? $data['borrow_nid'] : '';
        $sql .= "nid='{$data['nid']}',";
        $sql .= "borrow_nid='{$data['borrow_nid']}',";
        $sql .= "account_web_status='{$data['account_web_status']}',";
        $sql .= "account_user_status='{$data['account_user_status']}',";
        $sql .= "code='{$data['code']}',";
        $sql .= "code_type='{$data['code_type']}',";
        $sql .= "code_nid='{$data['code_nid']}',";
        $sql .= "user_id='{$data['user_id']}',";
        $sql .= "type='{$data['type']}',";
        $sql .= "money='{$data['money']}',";
        $sql .= "remark='{$data['remark']}',";
        $sql .= "to_userid='{$data['to_userid']}',";

        $sql .= "balance_cash_new='{$data['balance_cash']}',"; //可提现
        $sql .= "balance_cash_old='{$result['balance_cash']}',";
        $sql .= "balance_cash=balance_cash_new+balance_cash_old,";

        $sql .= "balance_frost_new='{$data['balance_frost']}',";//不可提现
        $sql .= "balance_frost_old='{$result['balance_frost']}',";
        $sql .= "balance_frost=balance_frost_new+balance_frost_old,";

        $sql .= "balance_new=balance_cash_new+balance_frost_new,";//可用余额
        $sql .= "balance_old='{$result['balance']}',";
        $sql .= "balance=balance_new+balance_old,";

        $sql .= "income_new='{$data['income']}',";
        $sql .= "income_old='{$result['income']}',";
        $sql .= "income=income_new+income_old,";

        $sql .= "expend_new='{$data['expend']}',";
        $sql .= "expend_old='{$result['expend']}',";
        $sql .= "expend=expend_new+expend_old,";

        $sql .= "frost_new='{$data['frost']}',";//冻结金额
        $sql .= "frost_old='{$result['frost']}',";
        $sql .= "frost=frost_new+frost_old,";

        $sql .= "await_new='{$data['await']}',";
        $sql .= "await_old='{$result['await']}',";
        $sql .= "await=await_new+await_old,";

        $repay = $data['repay'] ?: 0;
        $sql .= "repay_new='{$repay}',";
        $sql .= "repay_old='{$repay}',";
        $sql .= "repay=repay_new+repay_old,";

        $sql .= "total_old='{$result['total']}',";
        $sql .= "total=balance+frost+await,";
        $sql .= " `addtime` = '" . time() . "',`addip` = '" . get_client_ip() . "'";
        if (isset($data["user_id"]) && $data["user_id"] > 0) {
            db()->execute($sql);
            $id = db()->getLastInsID();
            if (!$id) {
                return ['code' => 0, 'msg' => "添加记录失败"];
            }

            $result = db('account_log')->where(['user_id' => $data['user_id'], 'id' => $id])->find();

            //第四步，更新用户表
            $sql = "update `{$prefix}account` set income={$result['income']},expend='{$result['expend']}',";
            $sql .= "balance_cash={$result['balance_cash']},balance_frost={$result['balance_frost']},";
            $sql .= "frost={$result['frost']},";
            $sql .= "await={$result['await']},";
            $sql .= "balance={$result['balance']},";
            $sql .= "repay={$result['repay']},";
            $sql .= "total={$result['total']}";
            $sql .= " where user_id='{$data['user_id']}'";
            $ex = db()->execute($sql);
            if (!$ex) {
                return ['code' => 0, 'msg' => "更新用户失败"];
            }

        }

        //第三步，加入总费用
        $result = db('account_balance')->where(['nid' => $data['nid']])->find();
        if (!$result) {
            //加入网站的财务表
            $result = db('account_balance')->order('id desc')->find();
            if (!$result) {
                $result['total'] = 0;
                $result['balance'] = 0;
            }
            $total = $result['total'] + $data['income'] + $data['expend'];
            $sql = "insert into `{$prefix}account_balance` set total='{$total}',balance={$result['balance']}+" . $data['income'] . ",income='{$data['income']}',expend='{$data['expend']}',type='{$data['type']}',`money`='{$data['money']}',user_id='{$data['user_id']}',nid='{$data['nid']}',remark='{$data['remark']}', `addtime` = '" . time() . "',`addip` = '" . get_client_ip() . "'";
            $ex = db()->execute($sql);
            if (!$ex) {
                return ['code' => 0, 'msg' => "操作失败"];
            }
        }

        if ($data['account_web_status'] == 1) {
            //第三步，加入用户的总费用
            $result = db('account_web')->where(['nid' => $data['nid']])->find();
            if (!$result) {
                //加入用户的财务表
                $result = db('account_web')->order('id desc')->find();
                if (!$result) {
                    $result['total'] = 0;
                    $result['balance'] = 0;
                }
                $total = $result['total'] - $data['income'] + $data['expend'];
                $sql = "insert into `{$prefix}account_web` set total='{$total}',balance={$result['balance']}-" . $data['income'] . "+" . $data['expend'] . ",income='{$data['income']}',expend='{$data['expend']}',type='{$data['type']}',`money`='{$data['money']}',user_id='{$data['user_id']}',nid='{$data['nid']}',remark='{$data['remark']}', `addtime` = '" . time() . "',`addip` = '" . get_client_ip() . "'";
                $ex = db()->execute($sql);
                if (!$ex) {
                    return ['code' => 0, 'msg' => "操作失败"];
                }
            }
        }

        if ($data['account_user_status'] == 1) {
            //第三步，加入用户的总费用
            $result = db('account_users')->where(['nid' => $data['nid']])->find();
            if (!$result) {
                //加入用户的财务表
                $_result = db('account_users')->order('id desc')->find();
                if (!$_result) {
                    $_result['total'] = 0;
                    $_result['balance'] = 0;
                }
                $total = $_result['total'] + $data['income'] - $data['expend'];
                $sql = "insert into `{$prefix}account_users` set total='{$total}',balance={$_result['balance']}+" . $data['income'] . "-" . $data['expend'] . ",income='{$data['income']}',expend='{$data['expend']}',type='{$data['type']}',`money`='{$data['money']}',user_id='{$data['user_id']}',nid='{$data['nid']}',remark='{$data['remark']}', `addtime` = '" . time() . "',`addip` = '" . get_client_ip() . "'";
                $ex = db()->execute($sql);
                if (!$ex) {
                    return ['code' => 0, 'msg' => "操作失败"];
                }
            }
        }
        return ['code' => 1, 'msg' => "操作成功"];
    }

    public function editPaypwd($data = []) {
        if (!isset($data['user_id']) || $data['user_id'] == '') {
            return ['code' => 0, 'msg' => '用户ID不能为空!'];
        }
        if (!isset($data['oldpwd']) || $data['oldpwd'] == '') {
            return ['code' => 0, 'msg' => '原密码不能为空!'];
        }
        if (!isset($data['pwd']) || $data['pwd'] == '') {
            return ['code' => 0, 'msg' => '密码不能为空!'];
        }
        if ($data['pwd'] != $data['cpwd']) {
            return ['code' => 0, 'msg' => '两次密码不一致!'];
        }
        if (strlen($data['pwd']) < 6 || strlen($data['pwd']) > 15) {
            return ['code' => 0, 'msg' => '密码长度必须为6-15位'];
        }
        $user = model('user')->getUser(['user_id' => $data['user_id']]);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在!'];
        }
        if ($user['paypassword'] != md5($data['oldpwd'])) {
            return ['code' => 0, 'msg' => '原交易密码不正确!'];
        }
        $re = model('user')->editPaypwd($data['user_id'], md5($data['pwd']));
        if ($re) {
            session('tb_paypwd_error_count', null);
            return ['code' => 1, 'msg' => '修改交易密码成功!'];
        } else {
            return ['code' => 0, 'msg' => '修改交易密码失败!'];
        }
    }
    public function setPaypwd($data = []) {
        if (!isset($data['user_id']) || $data['user_id'] == '') {
            return ['code' => 0, 'msg' => '用户ID不能为空!'];
        }
        if (!isset($data['pwd']) || $data['pwd'] == '') {
            return ['code' => 0, 'msg' => '密码不能为空!'];
        }
        if ($data['pwd'] != $data['cpwd']) {
            return ['code' => 0, 'msg' => '两次密码不一致!'];
        }
        if (strlen($data['pwd']) < 6 || strlen($data['pwd']) > 15) {
            return ['code' => 0, 'msg' => '密码长度必须为6-15位'];
        }
        if (!isset($data['code']) || $data['code'] == '') {
            return ['code' => 0, 'msg' => '验证码不能为空!'];
        }
        $imgcode = session('valicode');
        if ($imgcode != $data['code']) {
            return ['code' => 0, 'msg' => '图形验证码不正确!'];
        }
        $user = model('user')->getUser(['user_id' => $data['user_id']]);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在!'];
        }
        if ($user['paypassword'] != '') {
            return ['code' => 0, 'msg' => '您已设置过交易密码!'];
        }
        $re = model('user')->editPaypwd($data['user_id'], md5($data['pwd']));
        if ($re) {
            session('valicode', null);
            return ['code' => 1, 'msg' => '修改交易密码成功!'];
        } else {
            return ['code' => 0, 'msg' => '修改交易密码失败!'];
        }
    }

    //重置交易密码
    public function resetPaypwd($data = []) {
        if (!isset($data['phone']) || $data['phone'] == '') {
            return ['code' => 0, 'msg' => '手机号码不能为空!'];
        }
        if (!isset($data['type']) || $data['type'] == '') {
            return ['code' => 0, 'msg' => '类型type不能为空!'];
        }
        if (!isset($data['pwd']) || $data['pwd'] == '') {
            return ['code' => 0, 'msg' => '密码不能为空!'];
        }
        if (strlen($data['pwd']) < 6 || strlen($data['pwd']) > 15) {
            return ['code' => 0, 'msg' => '密码长度必须为6-15位'];
        }
        if (!isset($data['code']) || $data['code'] == '') {
            return ['code' => 0, 'msg' => 'code不能为空!'];
        }
        if (!isset($data['tk']) || $data['tk'] == '') {
            return ['code' => 0, 'msg' => 'tk不能为空!'];
        }
        $user = model('user')->getUser(['username' => $data['phone']]);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在!'];
        }
        if (md5($data['phone'] . $data['code']) != $data['tk']) {
            return ['code' => 0, 'msg' => 'tk不合法!'];
        }

        $re = model('user')->editPaypwd($user['user_id'], md5($data['pwd']));
        if ($re) {
            session('tb_paypwd_error_count', null);
            return ['code' => 1, 'msg' => '重置交易密码成功!'];
        } else {
            return ['code' => 0, 'msg' => '重置交易密码失败!'];
        }
    }

    //重置登陆密码
    public function resetPwd($data = []) {
        if (!isset($data['phone']) || $data['phone'] == '') {
            return ['code' => 0, 'msg' => '手机号码不能为空!'];
        }
        if (!isset($data['type']) || $data['type'] == '') {
            return ['code' => 0, 'msg' => '类型type不能为空!'];
        }
        if (!isset($data['pwd']) || $data['pwd'] == '') {
            return ['code' => 0, 'msg' => '密码不能为空!'];
        }
        if (strlen($data['pwd']) < 6 || strlen($data['pwd']) > 15) {
            return ['code' => 0, 'msg' => '密码长度必须为6-15位'];
        }
        if (!isset($data['code']) || $data['code'] == '') {
            return ['code' => 0, 'msg' => 'code不能为空!'];
        }
        if (!isset($data['tk']) || $data['tk'] == '') {
            return ['code' => 0, 'msg' => 'tk不能为空!'];
        }
        $user = model('user')->getUser(['phone' => $data['phone']]);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在!'];
        }

        if (md5($data['phone'] . $data['code']) != $data['tk']) {
            return ['code' => 0, 'msg' => 'tk不合法!'];
        }

        $re = model('user')->editPwd($user['user_id'], md5($data['pwd']));
        if ($re) {
            session('login_error_number_' . $user['username'], null);
            return ['code' => 1, 'msg' => '重置密码成功!'];
        } else {
            return ['code' => 0, 'msg' => '重置密码失败!'];
        }
    }

    /** 获取用户免费提现次数
     * @param array $data
     * @return string
     */
    function getFreeNum($data = []){
        if (!isset($data['user_id'])) {
            return null;
        }
        $num = 2; //默认每月免费两次
        $fday = strtotime(date("Y-m-01"));
        $lday = strtotime('+1 month ' . date('Y-m-01'));
        //减去当月已使用免费提现次数
        $used_num = db('account_cash')->where([
                'user_id' => $data['user_id'],
                'status' => ['in', '0,1'],
                'free' => 1,
                'addtime' => ['between', [$fday, $lday]]
        ])->count();
        $used_num = $used_num ?: 0;
        $num -= $used_num;
        return $num > 0 ? $num : 0;
    }

    //修改密码
    public function editPwd($data = []) {
        if (!isset($data['user_id']) || $data['user_id'] == '') {
            return ['code' => 0, 'msg' => '用户ID不能为空!'];
        }
        if (!isset($data['pwd']) || $data['pwd'] == '') {
            return ['code' => 0, 'msg' => '密码不能为空!'];
        }
        if (strlen($data['pwd']) < 6 || strlen($data['pwd']) > 15) {
            return ['code' => 0, 'msg' => '密码长度必须为6-15位'];
        }
        $user = model('user')->getUser(['user_id' => $data['user_id']]);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在!'];
        }
        $re = model('user')->editPwd($data['user_id'], md5($data['pwd']));
        if ($re) {
            session('login_error_number_' . $user['username'], null);
            return ['code' => 1, 'msg' => '修改密码成功!'];
        } else {
            return ['code' => 0, 'msg' => '修改密码失败!'];
        }
    }
}